var React = require('react');
var classNames = require('classnames');

var HeaderSearch = React.createClass({
    getInitialState: function(){
        return {
            types: [
                {name: 'works', label: '作品'},
                {name: 'users', label: '设计师'}/*,
                {name: 'material', label: '素材'}*/
            ],
            activeType: this.props.activeType,
            query: this.props.query
        }
    },
    render: function(){
        var selectedType = this._getSelected();
        var open= this.props.openSearch;
        return (
            <form className={classNames({enHide : true,"search left":true, "open-search": open})} action={this.props.action} method="get">
                <div className="btn-submit"  onClick={this._search}>
                </div>
                <input type="hidden" name="searchtype" value={selectedType.name} />
                <input ref='input' className="query" name="key"
                    value={this.state.query}
                    onChange={this._change}
                    placeholder="请输入你要查找的内容  |" type="text"/>
                <div className="cate">
                    <div className="title">
                        {selectedType.label}
                        <div className="space"></div>
                        <img src="/images/icon/search-down-arrow.svg" className="arrow" />
                    </div>
                    <ul className="select">
                        {
                            this.state.types.map(function(type, key){
                                return <li key={key} onClick={this._select.bind(this, type)}>{type.label}</li>
                            }.bind(this))
                        }
                    </ul>
                </div>
            </form>
        )
    },
    _search: function(){
       if(this.props.openSearch){
           location.href = '/community/search?searchtype=' + this._getSelected().name + '&key=' + encodeURIComponent(this.state.query);
       }else{
           if(this.props.toggleOpen){
              this.props.toggleOpen();
           }
       }
    }, 
    _getSelected: function(){
        var name = this.state.activeType || '',
            types = this.state.types,
            ret = null;
        for(var i = 0, len = types.length; i< len;i++){
            if(types[i].name == name){
                ret = types[i];
            }
        }
        return ret ? ret: types[0];
    },
    _select: function(type){
        this.setState({
            activeType: type.name
        })
    },
    _change: function(event){
        var t = event.nativeEvent.target;
        this.setState({
            query: t.value
        });
    },
    getValue : function () {
        return this.refs.input.value;
    }
});

module.exports = HeaderSearch;
